﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////


#include "GnufExplorerBlockManager.h"
#include "GnufFamilyTreeNodeUtil.h"
#include "GnufModelViewDefine.h"
#include "GnufInfo.h"
#include "GnufTree.h"
#include "IUiDocument.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gfam;
using namespace gnuf;

ExplorerTreeNodeDelegate::ExplorerTreeNodeDelegate(TreeNode* pNode, ExplorerTreeNodeDelegate* parent /*= nullptr*/, bool deleteOnEmpty/* = true*/)
    : m_node(pNode), m_deleteOnEmpty(deleteOnEmpty), m_parent(parent), m_visited(true)
{
    if (m_node != nullptr)
    {
        std::vector<TreeNode*> subNodes = m_node->rawSubNodes();
        FOR_EACH(node, subNodes)
        {
            gcmp::OwnerPtr<ExplorerTreeNodeDelegate> subDelegate = NEW_AS_OWNER_PTR(ExplorerTreeNodeDelegate, node, this);
            subDelegate->m_visited = false;
            m_subNodeDelegates.push_back(std::move(subDelegate));
        }
    }
}

ExplorerTreeNodeDelegate::~ExplorerTreeNodeDelegate()
{
}

ExplorerTreeNodeDelegate* ExplorerTreeNodeDelegate::addSubNode(const std::wstring& name, bool& existed)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(m_node, L"m_node is nullptr", L"paramodel", L"2024-02-20");

    TreeNode* pSub = m_node->findSubItem(0, name);
    if (pSub != nullptr)
    {
        auto itr = std::find_if(m_subNodeDelegates.begin(), m_subNodeDelegates.end(), [&](const gcmp::OwnerPtr<ExplorerTreeNodeDelegate>& _one) {
            return _one->getDelegatedNode() == pSub; });
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(itr != m_subNodeDelegates.end(), L"impossible situation", L"paramodel", L"2024-02-20");

        (*itr)->m_visited = true;
        if (m_parent != nullptr)
        {
            m_parent->onSubNodeVisited(this);
        }
        existed = true;
        return (*itr).get();
    }

    pSub = m_node->addSubNode();
    gcmp::OwnerPtr<ExplorerTreeNodeDelegate> subDelegate = NEW_AS_OWNER_PTR(ExplorerTreeNodeDelegate, pSub, this);
    m_subNodeDelegates.push_back(std::move(subDelegate));

    if (m_parent != nullptr)
    {
        m_parent->onSubNodeVisited(this);
    }
    existed = false;
    return m_subNodeDelegates.back().get();
}

TreeNode* ExplorerTreeNodeDelegate::getDelegatedNode() const
{
    return m_node;
}

void ExplorerTreeNodeDelegate::onSubNodeVisited(ExplorerTreeNodeDelegate* pNode)
{
}

void gfam::ExplorerTreeNodeDelegate::unload()
{
    if (m_node == nullptr)
    {
        DBG_WARN(L"imposibble situaition happened", L"paramodel", L"2024-02-20");
        return;
    }

    if (!m_visited)
    {
        m_node->deleteSelf();
        return;
    }

    if (!m_node->isLeaf())
    {
        for (auto itr = m_subNodeDelegates.begin(); itr != m_subNodeDelegates.end(); ++itr)
        {
            gcmp::OwnerPtr<ExplorerTreeNodeDelegate>& subDelegate = *itr;
            if (subDelegate.get() != nullptr) subDelegate->unload();
        }

        if (m_node->isLeaf() && m_deleteOnEmpty) m_node->deleteSelf();
    }
}

ExplorerBlockManager::ExplorerBlockManager()
{
}

gfam::ExplorerBlockManager::~ExplorerBlockManager()
{

}

void gfam::ExplorerBlockManager::initBlocks(gnuf::TreeBoard* treeBoard)
{
    m_tree = treeBoard;
    destroyBlocks();

    FOR_EACH(block, m_staticBlocks) block->initBlock(m_tree);
    FOR_EACH(area, m_dynamicAreas) area->initArea(m_tree);
}

void gfam::ExplorerBlockManager::refresh(gcmp::IUiDocument* pUiDocument)
{
    load();
    refreshBlocks(pUiDocument);
    unLoad();
}

void gfam::ExplorerBlockManager::load()
{
    FOR_EACH(block, m_staticBlocks) block->loadTreeNodeDelegate();
    FOR_EACH(area, m_dynamicAreas) area->loadDyanmicBlocks();
}

void gfam::ExplorerBlockManager::unLoad()
{
    FOR_EACH(block, m_staticBlocks) block->unLoadTreeNodeDelegate();
    FOR_EACH(area, m_dynamicAreas) area->unLoadDynamicBlocks();
}

void gfam::ExplorerBlockManager::refreshBlocks(gcmp::IUiDocument* pUiDoc)
{
    FOR_EACH(block, m_staticBlocks) block->refresh(pUiDoc);
    FOR_EACH(area, m_dynamicAreas) area->refresh(pUiDoc);
}

void gfam::ExplorerBlockManager::registerStaticBlock(gcmp::OwnerPtr<StaticExplorerBlock> block)
{
    m_staticBlocks.push_back(std::move(block));
}

void ExplorerBlockManager::registerStaticBlockFront(gcmp::OwnerPtr<StaticExplorerBlock> block)
{
    m_staticBlocks.push_front(std::move(block));
}

void ExplorerBlockManager::removeProjectStaticBlock()
{
    m_staticBlocks.remove_if([](const gcmp::OwnerPtr<StaticExplorerBlock>& block) -> bool
    {
        auto blockName = block->getBlockName();
        if ((blockName == GnufModelViewTypeUtil::GetModelViewTypeName(PlanViewType))
            || (blockName == GnufModelViewTypeUtil::GetModelViewTypeName(View3DViewType))
            || (blockName == GnufModelViewTypeUtil::GetModelViewTypeName(ElevationViewType))
            || (blockName == GnufModelViewTypeUtil::GetModelViewTypeName(CeilingViewType))
            || (blockName == FAMILY_TEXT))
        {
            return false;
        }
        else
        {
            return true;
        }
    });
}

void gfam::ExplorerBlockManager::registerDynamicArea(gcmp::OwnerPtr<DynamicExplorerArea> area)
{
    m_dynamicAreas.push_back(std::move(area));
}

gfam::ExplorerBlockManager* gfam::ExplorerBlockManager::getInstance()
{
    static ExplorerBlockManager manager;
    return &manager;
}

void gfam::ExplorerBlockManager::destroyBlocks()
{
    FOR_EACH(area, m_dynamicAreas)
    {
        if (area)
        {
            area->clearDynamicBlocks();
        }
    }

    if (m_tree)
    {
        m_tree->clear();
    }
}

const gfam::ExplorerBlock* gfam::ExplorerBlockManager::findSourceBlock(const gcmp::IElement* src)
{
    FOR_EACH(block, m_staticBlocks)
    {
        if (const ExplorerBlock* pBlock = block->findSource(src)) return pBlock;
    }
    FOR_EACH(area, m_dynamicAreas)
    {
        if (const ExplorerBlock* pBlock = area->findSource(src)) return pBlock;
    }
    return nullptr;
}
